//百度EmailSpider V1.2 2012.7

//陈博伟 fedora下界面乱码 2013.1
// 2015-08-29 之前把代码 copy 到了新文件，以去除非法字符之类的报错
// 会到某一行卡住呢。可以搞搞回调 http://tieba.baidu.com/p/1759603854?pn=1
// test http://tieba.baidu.com/p/3483432704?pn=66

/*
2016-12-18 V1.3
几个框框里填上默认值；
页数范围框宽度弄大了一些：tf_range_from.setColumns(4);
结束后用关联的程序打开 EmailOutput.txt // TODO 在 Windows / Linux 测试
 */

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class BaiduEmailSpider implements WindowListener {

	private String THE_REGEX = "[a-zA-Z0-9]+([._-]\\w+)*@\\w+(\\.[a-zA-Z0-9]{1,})+";
	private String TITLE = "百度贴吧邮箱提取器V1.3";

	private Frame f;

	private Label lb_manual;
	private TextField tf_url;
	private Label lb_range_cong, lb_range_yedao, lb_range_ye;
	private TextField tf_range_from, tf_range_to;
	private Label lb_process;
	private Button bt_start, bt52;


	final private Font uniFont = new Font("微软雅黑", Font.PLAIN, 14);
	final private int FWIDTH = 500, FHEIGHT = 170, GAP = 25, LBHEIGHT = 20;
	final private Dimension wideDimension = new Dimension(FWIDTH - 2 * GAP, LBHEIGHT);

	class Kaimoji {
		private static final String Working = "≧o≦";
		private static final String Error = "oдo";
		private static final String Dai = "-д-";
		private static final String Done = "^ω^";
	}

	class Button_Start implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			System.out.println("从|" + tf_range_from.getText() + "|到|" + tf_range_to.getText() + "|.");
			if(isGoodBaiduURL(tf_url.getText())) {
				try {
					BufferedWriter bw = new BufferedWriter(new FileWriter("EmailOutput.txt"));
					for(
							int i = Integer.parseInt(tf_range_from.getText());
							(i <= Integer.parseInt(tf_range_to.getText()));
							i++) {
						boolean existPage = true;
						lb_process.setText(("开始读取第" + String.valueOf(i) + "页" + Kaimoji.Working));

						URL url = new URL(tf_url.getText() + "?pn=" + String.valueOf(i));
						try {
							url.openStream();
						} catch (Exception e1) {
							lb_process.setText("连接打不开" + Kaimoji.Error);
							url = null;
							break;
						}

						HttpURLConnection connection = (HttpURLConnection) url.openConnection();
						InputStream is = connection.getInputStream();
						BufferedReader br = new BufferedReader(new InputStreamReader(is));
						String line = "";

						/*
						while ((line = br.readLine()) != null) {
							if(isTitleBaiduTieba(line)){
								System.out.println("BDTB");
								existPage=false;
								break;
							}
						}
						
						is=connection.getInputStream();
						br=new BufferedReader(new InputStreamReader(is));
						*/
						int lineNumber = 1;
						if(existPage) {
							while((line = br.readLine()) != null) {
								parse(line, bw);
								System.out.println(lineNumber + "行");
								lineNumber++;
							}
						} else {
							lb_process.setText("第" + String.valueOf(i) + "页已经不存在，停止读取");
							System.out.println("第" + String.valueOf(i) + "页已经不存在，停止读取");
						}
					}

					bw.flush();
					bw.close();
					lb_process.setText("读取结束，结果保存在同一目录下的EmailOutput.txt文件" + Kaimoji.Done);

//					Runtime.getRuntime().exec("start EmailOutput.txt"); // Windows
//					Runtime.getRuntime().exec("open EmailOutput.txt"); // macOS
					if(Desktop.isDesktopSupported()) {
						Desktop.getDesktop().open(new File("EmailOutput.txt"));
					}
				} catch (FileNotFoundException f) {
					f.printStackTrace();
				} catch (IOException i) {
					i.printStackTrace();
				}
			} else {
				lb_process.setText("帖子链接格式不正确,请重新输入" + Kaimoji.Dai);
			}
		}

		private void parse(String line, BufferedWriter bw) {

			Pattern p = Pattern.compile(THE_REGEX);
			Matcher m = p.matcher(line);

			while(m.find()) {
				System.out.println("find");
				lb_process.setText((m.group()));
				try {
					bw.write(m.group() + ";");
					bw.newLine();
					//win是\r\n，linux是\n。酱紫移植性好。
				} catch (IOException e) {
					e.printStackTrace();
				}

			}
		}

		private boolean isGoodBaiduURL(String url) {

			Pattern p = Pattern.compile("http://tieba.baidu.com/p/\\d*");
			Matcher m = p.matcher(url);
			if(m.find() && url.equals(m.group())) {
				return true;
			} else {
				return false;
			}
		}
		/*
		private boolean isTitleBaiduTieba(String line){
			Pattern p = Pattern.compile("<title>百度贴吧</title>");
			Matcher m = p.matcher(line);
			if(m.find()){
				return true;
			}
			else{
				return false;
			}
		}
		*/
	}

	class Button_Cancel implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			lb_manual.setText("人家，人家停不下来了啦！>_<");
		}

	}


	public BaiduEmailSpider() {

		f = new Frame(TITLE);
		f.addWindowListener(this);
		f.setSize(FWIDTH, FHEIGHT);
//        f.setResizable(false);
		f.setLayout(new FlowLayout());
		f.setBackground(Color.PINK);

		f.setLayout(new FlowLayout(FlowLayout.CENTER));

		Toolkit kit = Toolkit.getDefaultToolkit(); //添加标题栏图标
		Image img = kit.getImage("img\\AC弟 15.png");
		f.setIconImage(img);

		// 放到最后，否则里面内容不显示出来…… 当年少将提醒来着。2015-08-29
//        f.setVisible(true);

		lb_manual = new Label("请输入 http://tieba.baidu.com/p/4700482293 这种格式的帖子地址：");
		lb_manual.setFont(uniFont);
		lb_manual.setPreferredSize(wideDimension);


		tf_url = new TextField("http://tieba.baidu.com/p/4700482293");
		tf_url.setFont(uniFont);
		tf_url.setPreferredSize(wideDimension);

		lb_range_cong = new Label("从第");
		lb_range_cong.setFont(uniFont);

		tf_range_from = new TextField("1");
		tf_range_from.setFont(uniFont);
		tf_range_from.setColumns(4);

		lb_range_yedao = new Label("页到第");
		lb_range_yedao.setFont(uniFont);

		tf_range_to = new TextField("1");
		tf_range_to.setFont(uniFont);
		tf_range_to.setColumns(4);

		lb_range_ye = new Label("页");
		lb_range_ye.setFont(uniFont);

		lb_process = new Label("进度：");
		lb_process.setFont(uniFont);
		lb_process.setPreferredSize(wideDimension);

		bt_start = new Button("开始提取");
		bt_start.addActionListener(new Button_Start());
		bt_start.setFont(uniFont);

		bt52 = new Button("停止提取");
		bt52.addActionListener(new Button_Cancel());
		bt52.setFont(uniFont);


		f.add(lb_manual);
		f.add(tf_url);
		f.add(lb_range_cong);
		f.add(tf_range_from);
		f.add(lb_range_yedao);
		f.add(tf_range_to);
		f.add(lb_range_ye);
		f.add(lb_process);
		f.add(bt_start);
		//f.add(bt52);

		f.setVisible(true);
	}

	public static void main(String[] args) {
		System.out.println("before new BaiduEmailSpider();");
		new BaiduEmailSpider();
		System.out.println("after new BaiduEmailSpider();");
	}


	@Override
	public void windowActivated(WindowEvent e) {
	}

	@Override
	public void windowClosed(WindowEvent e) {
	}

	@Override
	public void windowClosing(WindowEvent e) {
		System.exit(0);
	}

	@Override
	public void windowDeactivated(WindowEvent e) {
	}

	@Override
	public void windowDeiconified(WindowEvent e) {
	}

	@Override
	public void windowIconified(WindowEvent e) {
	}

	@Override
	public void windowOpened(WindowEvent e) {
	}
}